#include "Data.h"
#include "Locate.h"

extern int numFrame;

Locate::Locate(Camera *camera) {
    this->cam = camera;
}

Locate::Locate(const Locate & orig) {
}

Locate::~Locate() {
}

void Locate::floodFill(float val, int X, int Y, int & min_x, int & min_y, int & max_x, int & max_y)
{   //从(X, Y)点开始将所有相邻的同色区域填充为val
    float ins = cvmGet(scanMat, Y, X);
    CvPoint drc[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}, tmp = {X, Y};
    cvmSet(scanMat, Y, X, val);
    min_x = max_x = X;min_y = max_y = Y;
    while(!Q.empty()) Q.pop();
    Q.push(tmp);
    while(!Q.empty())
    {
        for(int k = 0; k < 4; ++k)      //枚举四个方向
        {
            int x = Q.front().x + drc[k].x, y = Q.front().y + drc[k].y;
            if(x < 0 || x >= scanMat->width || y < 0 || y >= scanMat->height)
                continue;
            if(cvmGet(scanMat, y, x) == ins)
            {
                //将遍历到的点加入队列
                cvmSet(scanMat, y, x, val);
                tmp.x = x;
                tmp.y = y;
                Q.push(tmp);
                if(min_x > x) min_x = x;
                if(min_y > y) min_y = y;
                if(max_x < x) max_x = x;
                if(max_y < y) max_y = y;
            }
        }
        Q.pop();
    }
}

void Locate::scan(CvMat * mat)
{
    scanMat = cvCloneMat(mat);
    trackObject tmp;
    V.clear();
    int cnt = 0;
    for(int y = 0; y < mat->height; ++y)
    {
        for(int x = 0; x < mat->width; ++x)
        {
            if(cvmGet(scanMat, y, x) == 255)
            //if(cvmGet(scanMat, y, x) == 0)
            {   //floodFill填充待检测区域
                floodFill(0, x, y, tmp.pt0.x, tmp.pt0.y, tmp.pt1.x, tmp.pt1.y);
                //floodFill(255, x, y, tmp.pt0.x, tmp.pt0.y, tmp.pt1.x, tmp.pt1.y);
                if(tmp.pt1.x - tmp.pt0.x < 4 || tmp.pt1.y - tmp.pt0.y < 4)
                    continue;
                tmp.id = cnt++;
                tmp.rect = cvRect(tmp.pt0.x, tmp.pt0.y,
                        tmp.pt1.x - tmp.pt0.x + 1, tmp.pt1.y - tmp.pt0.y + 1);
                V.push_back(tmp);               //将检测到的区域加入列表
                //printf("%d %d %d %d\n", tmp.pt0.x, tmp.pt0.y, tmp.pt1.x, tmp.pt1.y);
            }
            if(cnt == 10) break;
            //cout<< *(mat->data.fl + y * mat->width + x) << "  ";
        }
        if(cnt == 10) break;
    }
    printf("Frame:%d\t Object:%d\n", numFrame, cnt);
    cvReleaseMat(&scanMat);
//    cvReleaseImage(&tmpScan);
//    scanImg.~Image();
}

void Locate::Draw(IplImage * image, CvScalar color)
{
    for(int i = 0; i < V.size(); ++i)
    {
//        if(V[i].lostfrm) continue;
        cvRectangle(image, V[i].pt0, V[i].pt1, color);
    }
}